package com.gzhryc.servlet;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.BrowserType;
import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.entity.ContentType;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class WebUtils {

    public static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
    public static final String HTTP_DATE_GMT_TIMEZONE = "GMT";
    public static final int HTTP_CACHE_SECONDS = 43200;

    static Logger log = Logger.getLogger(WebUtils.class);

    public static <T> T getParameter(HttpServletRequest request, Class<T> clazz) {
        try {
            T obj = clazz.newInstance();
            Map<String,String[]> map = getParameter(request);
            return ClassTools.setValues(obj,map);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T getParameter(HttpServletRequest request, Class<T> clazz, String... names) {
        try {
            T obj = clazz.newInstance();
            Map<String,String[]> map = getParameter(request);
            return ClassTools.setValues(obj, map, names);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T getParameter(HttpServletRequest request, String prefixName, Class<T> clazz) {
        try {
            T obj = clazz.newInstance();
            Map<String,String[]> data = new HashMap<String, String[]>();
            Map<String,String[]> map = request.getParameterMap();
            int index = prefixName.length() + 1;
            for (String key : map.keySet()) {
                if (key.startsWith(prefixName)) {
                    String[] values = map.get(key);
                    if(values != null && values.length > 0){
                        for(int i=0;i<values.length;i++){
                            values[i] = values[i].trim();
                        }
                    }
                    data.put(key.substring(index), values);
                }
            }
            return ClassTools.setValues(obj, data);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将空的Boolean属性设置为空
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> T setBooleanNullToFalse(T obj){
        Field[] fields = ClassTools.getDeclaredFields(obj.getClass());
        if(fields != null && fields.length > 0){
            for(Field field : fields){
                if(Boolean.class.equals(field.getType()) || boolean.class.equals(field.getType())){
                    try {
                        field.setAccessible(true);
                        Object temp = field.get(obj);
                        if(temp == null){
                            field.set(obj, ClassTools.toType(field.getType(), false));
                        }
                    } catch (IllegalAccessException e) {
                        log.error(e.getMessage(),e);
                    }
                }
            }
        }
        return obj;
    }

    public static Map<String, String> getSingleParameter(HttpServletRequest request) {
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String[]> map = request.getParameterMap();

        for (String key : map.keySet()) {
            String[] temp = map.get(key);
            if (temp.length > 0) {
                data.put(key, temp[0].trim());
            }
        }
        return data;
    }

    public static Map<String, String> getSingleParameter(HttpServletRequest request, String prefixName) {
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String[]> map = request.getParameterMap();
        int index = prefixName.length() + 1;
        for (String key : map.keySet()) {
            if (key.startsWith(prefixName)) {
                String[] temp = map.get(key);
                if (temp.length > 0) {
                    data.put(key.substring(index), temp[0].trim());
                }
            }
        }
        return data;
    }

    public static Map<String,String[]> getParameter(HttpServletRequest request){
        Map<String,String[]> result = request.getParameterMap();
        if(result != null && result.size() > 0){
            for(String key : result.keySet()){
                String[] array = result.get(key);
                if(array != null && array.length > 0){
                    for(int i=0;i<array.length;i++){
                        array[i] = array[i].trim();
                    }
                }
            }
        }
        return result;
    }

    public static <T> T getParameter(List<FileItem> fileItems, Class<T> clazz) {
        try {
            T obj = clazz.newInstance();
            if (fileItems != null) {
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {
                        try {
                            ClassTools.setFieldValue(obj, fileItem.getFieldName(), fileItem.getString("UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ClassTools.setFieldValue(obj, fileItem.getFieldName(), fileItem);
                    }
                }
            }
            return obj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> getParameters(HttpServletRequest request, String name, Class<T> clazz) {
        String[] params = request.getParameterValues(name);
        if (params != null) {
            List<T> result = new ArrayList<T>();
            for (int i = 0; i < params.length; i++) {
                result.add(ClassTools.toType(clazz, params[i].trim()));
            }
            return result;
        }
        return null;
    }

    public static String getStream2String(HttpServletRequest request) {
        return getStream2String(request, Charset.forName("UTF-8"));
    }

    public static String getStream2String(HttpServletRequest request, String charsetName) {
        return getStream2String(request, Charset.forName(charsetName));
    }

    public static String getStream2String(HttpServletRequest request, Charset charset) {
        final StringBuffer buffer = new StringBuffer("");
        try {
            final Reader reader = new InputStreamReader(request.getInputStream(), charset);

            final char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static Long getLong(HttpServletRequest request, String name) {
        return getLong(request, name, null);
    }

    public static Long getLong(HttpServletRequest request, String name, Long defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isBlank(temp)) {
            Object obj = request.getAttribute(name);
            if (obj != null) {
                temp = obj.toString();
            }
        }
        if (StringUtils.isNumeric(temp)) {
            return Long.valueOf(temp);
        }
        return defaultValue;
    }

    public static Integer getInteger(HttpServletRequest request, String name) {
        return getInteger(request, name, null);
    }

    public static Integer getInteger(HttpServletRequest request, String name, Integer defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isBlank(temp)) {
            Object obj = request.getAttribute(name);
            if (obj != null) {
                temp = obj.toString();
            }
        }
        if (StringUtils.isNumeric(temp)) {
            return Integer.valueOf(temp);
        }
        return defaultValue;
    }

    public static Double getDouble(HttpServletRequest request, String name) {
        return getDouble(request, name, null);
    }

    public static Double getDouble(HttpServletRequest request, String name, Double defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isBlank(temp)) {
            Object obj = request.getAttribute(name);
            if (obj != null) {
                temp = obj.toString();
            }
        }
        if (StringTools.isNumber(temp)) {
            return Double.valueOf(temp);
        }
        return defaultValue;
    }

    public static Boolean getBoolean(HttpServletRequest request, String name) {
        return getBoolean(request, name, null);
    }

    public static Boolean getBoolean(HttpServletRequest request, String name, Boolean defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isBlank(temp)) {
            Object obj = request.getAttribute(name);
            if (obj != null) {
                temp = obj.toString();
            }
        }

        if (StringUtils.isNotBlank(temp)) {
            return Boolean.valueOf(temp);
        }
        return defaultValue;
    }

    public static String getString(HttpServletRequest request, String name) {
        return getString(request, name, null);
    }

    public static String getString(HttpServletRequest request, String name, String defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isNotBlank(temp)) {
            return temp.trim(); // 去空格
        } else {
            Object obj = request.getAttribute(name);
            if (obj != null) {
                return obj.toString().trim(); // 去空格
            }
        }
        return defaultValue;
    }

    public static Date getDate(HttpServletRequest request, String name){
        String temp = getString(request,name);
        if(StringUtils.isNotBlank(temp)){
            try {
                return DateUtils.parseDate(temp,"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd");
            } catch (ParseException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public static <T> T getAttribute(HttpSession session, String name, Class<T> clazz) {
        Object obj = session.getAttribute(name);
        if (obj != null) {
            return ClassTools.toType(clazz, obj);
        }
        return null;
    }

    public static <T> T getAttribute(HttpServletRequest request, String name, Class<T> clazz) {
        Object obj = request.getAttribute(name);
        if (obj != null) {
            return ClassTools.toType(clazz, obj);
        }
        return null;
    }

    public static void setAttribute(HttpServletRequest request, Object obj) {
        if (obj != null) {
            Map<String, Object> data = ClassTools.findDeclaredGetMethodValues(obj, obj.getClass(), null);
            if (data != null && data.size() > 0) {
                for (String key : data.keySet()) {
                    request.setAttribute(key, data.get(key));
                }
            }
        }
    }

    public static void toJson(HttpServletResponse resp, Object obj) {
        if (!String.class.equals(obj.getClass())) {
            obj = JsonTools.toJson(obj);
        }
        resp.setCharacterEncoding("UTF-8");
        resp.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        try {
            resp.getOutputStream().write(obj.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isJsonAccept(HttpServletRequest request) {
        String accept = request.getHeader(HttpHeaders.ACCEPT);
        if (StringUtils.isNotBlank(accept)) {
            if (accept.contains(ContentType.APPLICATION_JSON.getMimeType())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isJsonContentType(HttpServletRequest request) {
        String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
        if (StringUtils.isNotBlank(contentType)) {
            if (contentType.contains(ContentType.APPLICATION_JSON.getMimeType())) {
                return true;
            }
        }
        log.error("无效的JSON请求头部，头部Content-Type：{{0}}",contentType);
        return false;
    }

    public static boolean isXMLContentType(HttpServletRequest request) {
        String accept = request.getHeader(HttpHeaders.CONTENT_TYPE);
        if (StringUtils.isNotBlank(accept)) {
            if (accept.contains(ContentType.TEXT_XML.getMimeType()) || accept.contains(ContentType.APPLICATION_XML.getMimeType())) {
                return true;
            }
        }
        return false;
    }

    public static <T> T getJsonRequest(HttpServletRequest request, Class<T> clazz) {
        if (isJsonContentType(request)) {
            String json = getStream2String(request);
            if (StringUtils.isNotBlank(json) && JsonTools.isJsonStr(json)) {
                try {
                    return JsonTools.fromJson(json, clazz);
                }catch (Exception e){
                    log.error("解析JSON字符串失败，内容：{{0}}",json);
                    log.error(e.getMessage(),e);
                }
            }else{
                log.error("无效的JSON字符串，内容：{{0}}",json);
            }
        }
        return null;
    }

    public static <T> T getForceJsonRequest(HttpServletRequest request, Class<T> clazz) {
        String json = getStream2String(request);
        if (StringUtils.isNotBlank(json) && JsonTools.isJsonStr(json)) {
            try {
                return JsonTools.fromJson(json, clazz);
            }catch (Exception e){
                log.error("解析JSON字符串失败，内容：{{0}}",json);
                log.error(e.getMessage(),e);
            }
        }else{
            log.error("无效的JSON字符串，内容：{{0}}",json);
        }
        return null;
    }

    /**
     * 设置导出Excel文件的头部
     *
     * @param response
     * @param fileName
     */
    public static void exportExcel(HttpServletResponse response, String fileName) {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            String temp = URLEncoder.encode(fileName, "UTF8");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(temp.getBytes("UTF-8"), "iso8859-1") + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出XML
     *
     * @param response
     * @param xml
     */
    public static void exportXML(HttpServletResponse response, String xml) {
        try {
            response.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_XML.getMimeType());
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(xml.getBytes("UTF-8"));
            response.getOutputStream().flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportHTML(HttpServletResponse response, String html) {
        try {
            response.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_HTML.getMimeType());
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(html.getBytes("UTF-8"));
            response.getOutputStream().flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportText(HttpServletResponse response, String text) {
        try {
            response.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(text.getBytes("UTF-8"));
            response.getOutputStream().flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportJson(HttpServletResponse response, String json) {
        try {
            response.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(json.getBytes("UTF-8"));
            response.getOutputStream().flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportJPEG(HttpServletResponse response) {
        response.setContentType("image/jpeg");
    }

    /**
     * 导出图片
     *
     * @param response
     * @param buffImg
     */
    public static void exportJPEG(HttpServletResponse response, BufferedImage buffImg) {
        response.setContentType("image/jpeg");
        try {
            ImageIO.write(buffImg, "jpeg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) {
        try {
            if (url.startsWith("http://") || url.startsWith("https://")) {
                response.sendRedirect(url);
            } else {
                Object webRoot = request.getAttribute("webRoot");
                if (webRoot != null) {
                    response.sendRedirect(webRoot + url);
                } else {
                    response.sendRedirect(request.getContextPath() + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void requestForward(HttpServletRequest request, HttpServletResponse response, String url) {
        try {
            if (url.startsWith("http://") || url.startsWith("https://")) {
                request.getRequestDispatcher(url).forward(request, response);
            } else {
                Object webRoot = request.getAttribute("webRoot");
                if (webRoot != null) {
                    request.getRequestDispatcher(webRoot + url).forward(request, response);
                } else {
                    request.getRequestDispatcher(url).forward(request, response);
                }
            }
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是手机和平板
     *
     * @param request
     * @return
     */
    public static boolean isMobileOrTablet(HttpServletRequest request) {
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        DeviceType deviceType = userAgent.getOperatingSystem().getDeviceType();
        return DeviceType.MOBILE.equals(deviceType) || DeviceType.TABLET.equals(deviceType);
    }

    public static boolean isBrowser(HttpServletRequest request) {
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        return BrowserType.WEB_BROWSER.equals(browser.getBrowserType()) || BrowserType.MOBILE_BROWSER.equals(browser.getBrowserType());
    }

    /**
     * 是否是支付宝访问
     *
     * @param request
     * @return
     */
    public static boolean isAlipayClient(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("AlipayClient")) {
            return true;
        }
        return false;
    }

    /**
     * 是否是微信小程序访问
     * TODO 判断不准确
     * @param request
     * @return
     */
    public static boolean isWxxcxClient(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("miniProgram")) {
            return true;
        }
        return false;
    }

    /**
     * 是否是微信端访问
     *
     * @param request
     * @return
     */
    public static boolean isWxClient(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("MicroMessenger")) {
            return true;
        }
        return false;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }

    /**
     * 获取当前请求域名
     *
     * @param request
     * @return
     */
    public static String getHttpDomain(HttpServletRequest request) {
        StringBuffer tempUrl = request.getRequestURL();
        tempUrl = tempUrl.delete(tempUrl.length() - request.getRequestURI().length(), tempUrl.length());
        return tempUrl.toString();
    }

    /**
     * 路径前添加当前请求域名
     *
     * @param request
     * @param url
     * @return
     */
    public static String setHttpDomain(HttpServletRequest request, String url) {
        if (StringUtils.isNotBlank(url) && !url.startsWith("http")) {
            StringBuffer tempUrl = request.getRequestURL();
            tempUrl = tempUrl.delete(tempUrl.length() - request.getRequestURI().length(), tempUrl.length());
            return tempUrl.append(url).toString();
        }
        return url;
    }

    public static String setHttpDomain(String httpDomain,String url) {
        if (StringUtils.isNotBlank(httpDomain) && StringUtils.isNotBlank(url) && !url.startsWith("http")) {
            return httpDomain + url;
        }
        return url;
    }

    public static String getRequestURI(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        if (StringUtils.isNotBlank(contextPath) && !contextPath.equals("/")) {
            return request.getRequestURI().replaceFirst(contextPath, "");
        }
        return request.getRequestURI();
    }

    /**
     * 获取当前请求的语言
     *
     * @param request
     * @return
     */
    public static String getLanguage(HttpServletRequest request) {
        String lang = request.getLocale().getLanguage();
        if(StringUtils.isBlank(lang)){lang = "zh";}
        return getString(request, "lang", lang);
    }

    /**
     * 根据文件后缀设置响应内容的类型
     *
     * @param response
     * @param filePath
     */
    public static void setResponseContentType(HttpServletResponse response, String filePath) {
        String fileExt = FilenameUtils.getExtension(filePath);
        if ("jpg".equals(fileExt) || "jpeg".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "image/jpeg");
        } else if ("png".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "image/png");
        } else if ("gif".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "image/gif");
        } else if ("pdf".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "application/pdf");
        } else if ("js".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "application/javascript");
        } else if ("css".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "text/css;charset=UTF-8");
        } else if ("woff".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "font/woff");
        } else if ("woff2".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "font/woff2");
        } else if ("mp3".equals(fileExt)) {
            response.addHeader(HttpHeaders.CONTENT_TYPE, "audio/mp3");
        } else if("svg".equals(fileExt)){
            response.addHeader(HttpHeaders.CONTENT_TYPE, "image/svg+xml");
        }else {
            log.error("未知文件后缀，" + fileExt);
            response.addHeader(HttpHeaders.CONTENT_TYPE, "*/*");
        }
    }

    /**
     * 读取静态资源
     *
     * @param response
     * @param filePath
     */
    public static void readResource(HttpServletResponse response, String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(file, "r");
                } catch (FileNotFoundException ignore) {
                    return;
                }

                Long fileLen = raf.length();

                setDateAndCacheHeaders(response, file);

                WritableByteChannel wbc = null;
                FileChannel fc = null;
                try {
                    fc = raf.getChannel();
                    wbc = Channels.newChannel(response.getOutputStream());
                    long len = fc.transferTo(0, fileLen, wbc);
                    response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(len));
                } finally {
                    if (raf != null) {
                        try {
                            raf.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fc != null) {
                        try {
                            fc.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取静态资源错误，路径：" + filePath, e);
        }
    }

    /**
     * 设置时间及缓存时间
     *
     * @param resp
     * @param fileToCache
     */
    public static void setDateAndCacheHeaders(HttpServletResponse resp, File fileToCache) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

        // Date header
        Calendar time = new GregorianCalendar();
        resp.addHeader(HttpHeaders.DATE, dateFormatter.format(time.getTime()));

        // Add cache headers
        time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
        resp.addHeader(HttpHeaders.EXPIRES, dateFormatter.format(time.getTime()));
        resp.addHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
        resp.addHeader(HttpHeaders.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
    }

    public static String getCookies(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
	        for (int i = 0; i < cookies.length; i++) {
	            String cookiesName = cookies[i].getName();
	            if (cookiesName.equals(key)) {
	                String value = cookies[i].getValue();
	                return value;
	            }
	        }
        }
        return null;
    }

    public static boolean checkCookiesValue(HttpServletRequest request, String key, String value) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
	        for (int i = 0; i < cookies.length; i++) {
	            String cookiesName = cookies[i].getName();
	            if (cookiesName.equals(key)) {
	                String cookieValue = cookies[i].getValue();
	                if (StringUtils.isNotBlank(cookieValue) && cookieValue.equals(value)) {
	                    return true;
	                }
	            }
	        }
        }
        return false;
    }

    public static void setCookies(HttpServletRequest request, HttpServletResponse response, String key, String value, Integer time) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath(getHttpDomain(request));
        cookie.setMaxAge(time);
        response.addCookie(cookie);
    }
}
